<template>
  <div class="signin-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleCreate">发布新签到</el-button>
      <el-input
        v-model="searchKey"
        placeholder="搜索签到标题"
        style="width: 300px; margin-left: 20px"
        clearable
        @input="handleSearchInput"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select 
        style="width:180px; margin-left: 20px" 
        v-model="signType" 
        @change="fetchData" 
        placeholder="签到类型"
      >
        <el-option label="全部" value="" />
        <el-option label="普通签到" value="普通" />
        <el-option label="签到码签到" value="签到码" />
        <el-option label="二维码签到" value="二维码" />
        <el-option label="位置签到" value="位置" />
        <el-option label="手势签到" value="手势" />
      </el-select>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%; margin-top: 20px"
      empty-text="暂无签到数据"
    >
      <el-table-column prop="title" label="签到标题" width="150" />
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="range" label="迟到范围" width="80">
        <template #default="scope">
        {{ scope.row.range }} 分钟
      </template>
      </el-table-column>
      <el-table-column prop="classes" label="参与班级" width="120">
      </el-table-column>
      <el-table-column prop="signType" label="签到类型" width="80">
        <template #default="scope">
        {{ scope.row.signType}}签到
      </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="success" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>

    <!-- 编辑/创建对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑签到' : '新建签到'"
      width="600"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="签到标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入签到标题" />
        </el-form-item>
        <el-form-item label="签到类型" prop="signType" v-if="!isEdit">
          <el-select 
            v-model="formData.signType" 
            placeholder="请选择签到类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 动态显示内容 -->
        <template v-if="formData.signType&&!isEdit">
          <el-form-item prop="frequency" key="location" v-if="formData.signType === '位置'">
            <LocationPicker ref="locationPickerRef" />
          </el-form-item>
        <!-- 确保v-model绑定 -->
        <el-form-item 
          prop="signCode" 
          key="code" 
          v-if="formData.signType === '签到码'"
          :rules="[
          { required: true, message: '请输入或生成签到码', trigger: 'change' },
          { pattern: /^\d{4}$/, message: '必须为4位数字', trigger: 'blur' }
          ]"
        >   
        <CodePicker 
          ref="codePickerRef" 
          v-model="formData.signCode" 
        />
      </el-form-item>
      <el-form-item 
          prop="signGesture" 
          key="gesture" 
          style="padding: 20px;"
          v-if="formData.signType === '手势'"
          :rules="[
          { required: true, message: '请绘制手势', trigger: 'change' },
          { min: 4, message: '至少需要4个方向点', trigger: 'blur' }
          ]"
        >
      <GesturePicker 
        ref="gesturePickerRef" 
        v-model="formData.signGesture" 
      />
    </el-form-item>
        </template>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="迟到范围" prop="range">
          <el-input v-model="formData.range" placeholder="请输入迟到范围" />
        </el-form-item>
        <el-form-item label="参与班级" prop="classId" v-if="!isEdit">
          <el-input v-model="formData.classId" placeholder="请输入班级号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'
import LocationPicker from '@/components/LocationPicker.vue'
import CodePicker from '@/components/CodePicker.vue';
import GesturePicker from '@/components/GesturePicker.vue'
import { debounce } from 'lodash-es';
import router from "@/router";

const API_BASE = 'http://localhost:8080/attendance'
const api = {
  list: `${API_BASE}/list`,
  create: `${API_BASE}/add`,
  update: id => `${API_BASE}/update/${id}`,
  delete: id => `${API_BASE}/delete/${id}`
}
const locationPickerRef = ref(null);
const codePickerRef = ref(null)
const gesturePickerRef = ref(null)

const typeOptions = [
  { value: '普通', label: '普通' },
  { value: '签到码', label: '签到码' },
  { value: '二维码', label: '二维码' },
  { value: '位置', label: '位置' },
  { value: '手势', label: '手势' }
]

// 状态管理
const tableData = ref([])
const loading = ref(false)
const searchKey = ref('')
const signType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const formData = reactive({
  sessionId: null,
  teacherId: '',
  title: '',
  signType: '',
  startTime: '',
  endTime: '',
  classId: '',
  range: null
})

// 表单验证规则
const formRules = {
  title: [{ required: true, message: '请输入签到标题', trigger: 'blur' }],
  signType: [{ required: true, message: '请选择签到类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  range: [{ required: true, message: '请选择签到范围', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  classes: [{ required: true, message: '请选择参与班级', trigger: 'change' }],
  // 在 formRules 中添加签到码规则
  signCode: [
    { required: true, message: '请输入或生成签到码', trigger: 'change' },
    { pattern: /^\d{4}$/, message: '必须为4位数字', trigger: 'blur' }
  ],
  signGesture: [
    { required: true, message: '请绘制并确认手势', trigger: 'change' },
    { min: 4, message: '至少需要4个方向点', trigger: 'blur' }
  ]
}

onMounted(() => {
  fetchData()
})
const handleSearchInput = debounce(() => {
  fetchData();
}, 500); // 500ms 防抖
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      title: searchKey.value,
      sessionType: signType.value
    }
    const response = await axios.get(api.list, { params })
    const pageData = response.data.data
    tableData.value = pageData.records.map(item => ({
      id: item.sessionId,
      teacherId: item.teacherId,
      title: item.title,
      startTime: item.startTime,
      endTime: item.endTime,
      range: item.lateRange,
      classes: item.classId, // 提取班级名称
      signType: item.sessionType,  // 保持原始值用于类型映射
    }))
    total.value = pageData.total
    currentPage.value = pageData.current
    pageSize.value = pageData.size
    // console.log(this.$ref.LocationPicker)
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

const formatTime = time => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const handleCreate = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = row => {
  isEdit.value = true
  Object.assign(formData, {
    sessionId: row.id,
    teacherId: row.teacherId,
    title: row.title,
    signType: row.signType,
    startTime: row.startTime,
    endTime: row.endTime,
    range: row.range,
    classId: row.classes,
  })
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    const payload = {
      teacherId: 'T001', // 假设教师ID为1
      title: formData.title,                 // 直接映射
      sessionType: formData.signType,        // 映射 signType -> sessionType
      startTime: new Date(formData.startTime), // 转换为 Date 类型
      endTime: new Date(formData.endTime),   // 转换为 Date 类型
      classId: formData.classId,   // 将数组拼接成字符串
      lateRange: formData.range,              // 映射 range -> lateRange
      signCode: formData.signType === '签到码' ? formData.signCode : undefined,
      signGesture: formData.signType === '手势' ? formData.signGesture : undefined
    }

    const url = isEdit.value ? api.update(formData.sessionId) : api.create
    const method = isEdit.value ? 'put' : 'post'
    // console.log(formData)
    if(formData.signType != '普通' && isEdit.value == false){
      if(formData.signType == '位置'){
      try {
        const result = await locationPickerRef.value.handleCreate();
        console.log('创建成功:', result);
      } catch (error) {
        console.error('创建失败:', error.message);
      }
    }

    if (formData.signType == '签到码') {
        try {
        const result = await codePickerRef.value.handleCreate();
        console.log('创建成功:', result);
      } catch (error) {
        console.error('创建失败:', error.message);
      }
    }

    if(formData.signType === '手势' && !isEdit.value) {
      try {
        await gesturePickerRef.value.handleCreate()
      } catch (error) {
        ElMessage.error('手势创建失败: ' + error.message)
        return
      }
    }
      if (formData.signType === '二维码') {
        try {
         router.push('/qrcode')
        } catch (error) {
          ElMessage.error('二维码创建失败: ' + error.message)
        }
    }

  }
    await axios[method](url, payload)

    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    if (!error) return
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleDelete = async id => {
  try {
    await ElMessageBox.confirm('确认删除该签到记录？此操作不可恢复！', '警告', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.delete(api.delete(id))
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    teacherId: '',
    title: '',
    signType: '',
    startTime: '',
    endTime: '',
    range: null,
    classId: '',
  })
  gesturePickerRef.value?.clearCanvas?.()
}


</script>

<style scoped>
.signin-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table__empty-block {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>